/*
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2022-04-21 20:16:34
 * @LastEditors: GGB
 * @LastEditTime: 2022-04-30 07:51:38
 */
/**
 * Multi-language related operations
 */
import type { LocaleType } from '/#/config'
import { i18n } from './setupI18n'
import { useLocaleStoreWithOut } from '/@/store/modules/locale'
import { unref, computed } from 'vue'
import { loadLocalePool } from './helper'
import zh_CN from './lang/zh_CN'
import en from './lang/en'

interface LangModule {
  message: Recordable
  momentLocale: Recordable
  momentLocaleName: string
}

function setI18nLanguage(locale: LocaleType) {
  const localeStore = useLocaleStoreWithOut()
  console.log('setI18nLanguage')
  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale
  } else {
    // eslint-disable-next-line @typescript-eslint/no-extra-semi
    ;(i18n.global.locale as any).value = locale
  }
  localeStore.setLocaleInfo({ locale })
}

export function useLocale() {
  const localeStore = useLocaleStoreWithOut()
  const getLocale = computed(() => localeStore.getLocale)

  // Switching the language will change the locale of useI18n
  // And submit to configuration modification
  async function changeLocale(locale: LocaleType) {
    const globalI18n = i18n.global
    const currentLocale = unref(globalI18n.locale)
    if (currentLocale === locale) {
      return locale
    }
    console.log('locale----', locale)
    console.log('loadLocalePool----', loadLocalePool)
    if (loadLocalePool.includes(locale)) {
      setI18nLanguage(locale)
      return locale
    }
    // const langModule = ((await import(`./lang/${locale}.ts`)) as any)
    //   .default as LangModule;
    // console.log("langModule----", langModule)---underfine;
    // TODO 这里做了特殊处理，由于小程序无法动态引入，所以需要手动引入，看下后期有没有好的方式处理这里
    const langModules: Record<string, any> = {
      en,
      zh_CN,
    }
    // if (!langModule) return;

    // const { message, momentLocale, momentLocaleName } = langModule;
    const { message } = langModules[locale] as LangModule

    globalI18n.setLocaleMessage(locale, message)
    loadLocalePool.push(locale)
    console.log('locale----', locale)
    setI18nLanguage(locale)
    return locale
  }

  return {
    getLocale,
    changeLocale,
  }
}
